//
//  WeChatManager.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/8.
//

import Foundation

class WeChatManager: NSObject, WXApiDelegate,ObservableObject {
    static let shared = WeChatManager()
    @Published var loginSuccess = WeChatLoginResult()
    @Published var isLoading = false
    @Published var error: String?
    struct WeChatLoginResult :Equatable {
        var accessToken: String?
        var openid: String?
        var unionid: String?
        var error: String?
    }
    
    // 发起微信登录
    func requestLogin() {
        let req = SendAuthReq()
        req.scope = "snsapi_userinfo"
        req.state = "随机状态值"
        WXApi.send(req) { Bool in
            print("登录返回"+String(Bool))
        }
    }
    
    // 清除微信授权
    func revokeAuthorization(for appID: String) {
        let req = WXLaunchMiniProgramReq()
        req.userName = appID
        req.path = "pages/revokeAuth/index"
        WXApi.send(req) { success in
            if success {
                
            }
        }
    }
    
    // 处理登录回调
    
    func onResp(_ resp: BaseResp) {
        if let authResp = resp as? SendAuthResp {
            if authResp.errCode == 0 {
                self.error = nil
                if let coed = authResp.code {
                    fetchOpenID(with: coed)
                }
            } else {
                self.error = "微信授权失败"
            }
        }
    }
    
    
    
    private func fetchOpenID(with code: String) {
        let url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx1dee817c3798bf26&secret=bee56f2c6d8c00004aa7db8493539bb6&code=\(code)&grant_type=authorization_code"
        URLSession.shared.dataTask(with: URL(string: url)!) { data, _, _ in
            if let data = data,
               let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
               let accessToken = json["access_token"] as? String,
               let openid = json["openid"] as? String,
               let unionid = json["unionid"] as? String{
                DispatchQueue.main.async {
                    print("获取到的OpenID: \(openid)")
                    print("获取到的accessToken: \(accessToken)")
                    print("获取到的unionid: \(unionid)")
                    // 存储或使用openid
                    self.error = nil
                    self.loginSuccess = WeChatLoginResult(
                        accessToken:accessToken,
                        openid:openid,
                        unionid:unionid
                    )
                }
            }else {
                self.error = "微信授权失败"
            }
        }.resume()
    }
}




